package com.globant.AutomateEMR;

	import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import com.globant.ErrorManager.ErrorLog;
	 
	public class AutomateImport{
		private PropertyLoader prop;
		
		public static final String FOLDER_EFFICIENTLOGS="LogsProcessed";
	    public PropertyLoader getProp() {
			return prop;
		}

		public void setProp(PropertyLoader prop) {
			this.prop = prop;
		}

		public AutomateImport( ) {
			super();
		}

		public AutomateImport(PropertyLoader prop) {
			super();
			this.prop = prop;
		}

//		public void storeInformationFromS3() throws IOException{
//			System.out.println("Storing Error Information..");
//			System.out.println("Checking Filesystem..");
//			File directory=new File(prop.readProperty("PathToBucket")+prop.readProperty("PathToAllProcessedInfo"));
//			System.out.println(directory.getName());
//			File[] intermediateFolders=directory.listFiles();
//			for(int i=0;i<intermediateFolders.length;i++){
//				 if(intermediateFolders[i].isDirectory() && intermediateFolders.length>0){ //ExtraInformation //Logs // LogsProcessed
//					this.moveExtraInformation(intermediateFolders[i]);
//				}
//			}
//		}
		
//		private void moveExtraInformation(File extraFolder) throws IOException {
//			FileManager fmg=new FileManager();
//			File[] filesInside=extraFolder.listFiles();
//			String path2Move="";
//			System.out.println("--"+extraFolder.getName());
//			for(int i=0;i<filesInside.length;i++){//newLogs ParsedLogs
//				if(filesInside[i].isDirectory()){
//					this.moveExtraInformation(filesInside[i]);
//				}else{
//					File renamedFile=new File(filesInside[i].getName()+"_"+this.getMoment());
//					filesInside[i].renameTo(renamedFile);
//					path2Move=getPath2Move(filesInside[i],extraFolder);
//					fmg.moveFile(filesInside[i], path2Move);
//				}
//			}			
//		}

//		private void storeInformationAndMove(File file) throws IOException {
//			File[] reportFolders=file.listFiles();
//			System.out.println("ooo-"+file);
//			for(int i=0;i<reportFolders.length;i++){//akn_session_fact akn_product_dim
//				this.storeAndMoveInformation(reportFolders[i]);
//				reportFolders[i].delete();
//			}
//		}


//		public void storeReportInformation(File reportFolder) throws IOException {
//			System.out.println("Storing and moving report...");
//			FileManager fmg=new FileManager();
//			String path2Move="";
//			File[] files=reportFolder.listFiles();
//			System.out.println("ooo-"+reportFolder);
//			for(int i=0;i<files.length;i++){//akn_session_fact akn_product_dim
//				this.importData(files[i].getPath(), reportFolder.getName());
//				File renamedFile=new File(files[i].getName()+"_"+this.getMoment());
//				files[i].renameTo(renamedFile);
//				path2Move=getPath2Move(files[i],reportFolder);
//				fmg.moveFile(files[i], path2Move);
//			}			
//		}
		
		/**
		 * @param file
		 * @param reportFolder
		 * @return /mnt/s3bucket/StoredLog/20130120/akn_session_fact/20120105_QueryReport_201301201205
		 * @throws IOException
		 */
//		public String getPath2Move(File file,File reportFolder) throws IOException {
//			String path2Move=this.getProp().readProperty("PathToBucket");
//			path2Move=path2Move+this.getProp().readProperty("PathToStoredLogs");
//			
//			//FOLDER DAY /20130506/
//			path2Move=path2Move+this.getDay()+"/";
//			File fday=new File(path2Move);
//			fday.mkdir();
//			System.out.println(path2Move);
//			
//			//SUPERIOR FOLDER /ExtraInformation/LogsProcessed
//			path2Move=path2Move+reportFolder.getName()+"/";			
//			File repFolder=new File(path2Move);
//			repFolder.mkdir();
//			System.out.println(path2Move);
//			
//			//path2Move=path2Move+file.getName();
//			//System.out.println(path2Move);
//			return path2Move;
//		}


//		private String getMoment() {
//			DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhss");
//			Calendar cal = Calendar.getInstance();
//			String today=dateFormat.format(cal.getTime());
//			return today;
//		}
//		public void importData(String path,String tablename){
//	    	getProp().loadProps();
//	    	DBase db = new DBase();
//	    	
//	    	String server=prop.getConfigProp().getProperty("MySqlServer");
//	    	String user=prop.getConfigProp().getProperty("MySqlUser");
//	    	String database=prop.getConfigProp().getProperty("MySqlDatabase");
//	    	String password=prop.getConfigProp().getProperty("MySqlPassword");
//	    	String port=prop.getConfigProp().getProperty("MySqlPort");
//	    	System.out.println(port);
//	        Connection conn = db.connect("jdbc:mysql://"+server+":"+port+"/"+database,user,password);
//	        db.importData(conn, path, tablename);
//	        System.out.println("Connected.Uploading Files to the database..");
//	        System.out.println("Finished!");
//		}

/*======================================== StoreErrorLog Methods ======================================================* */
		public ErrorLog storeErrorLog(ErrorLog errLog,FileManager fmg,String pathFromLogs,String pathToLogs,File logFile) throws IOException {
			System.out.println("Store errorLog");
			
//			File logFolder=new File(pathFromLogs);			
//			logFolder.mkdir();
//			File logFile=this.getLog(logFolder);
			
			String logFileId=fmg.generateLogId(logFile);
			errLog.setLogFileId(logFileId);
			System.out.println("LOGID"+logFileId);

			String today = getDay();
			String pathToMoveErrorLog=this.generateFolder2SaveLog(logFileId,pathToLogs,today);			
			System.out.println("MOVE TO"+pathToMoveErrorLog);
			
			fmg.moveFile(logFile, pathToMoveErrorLog);
			System.out.println("Moved: "+logFile.getName()+" to: "+pathToMoveErrorLog);
			
			errLog.setPathToS3(pathToMoveErrorLog);
						
			return errLog;
		}
		
/*-----------------------------------------------------------------------------------------------------------------*/
	public File getLog(File logFolder) {
			if(logFolder.isDirectory()){
				File[] files=logFolder.listFiles();
				for(int i=0;i<files.length;i++){
					if(!files[i].getName().equals(logFolder.getName())){
						return files[i];
					}
				}
			}
			return null;
	}

//			public String generateFolder2SaveErrorLogs(String logFileId) throws IOException{
////		public String generateFolder2SaveErrorLogs() throws IOException{
//			String pathToMoveErrorLog=prop.readProperty("PathToBucket")+prop.readProperty("PathToNotStoredLogs");
//			System.out.println(pathToMoveErrorLog);
//			
//			String today = getDay();
//			pathToMoveErrorLog=pathToMoveErrorLog+today+"/";
//			File folderToSave=new File(pathToMoveErrorLog);
//			folderToSave.mkdir();
//			System.out.println(pathToMoveErrorLog);
//			
//			pathToMoveErrorLog=pathToMoveErrorLog+logFileId+"/";
//			folderToSave=new File(pathToMoveErrorLog);
//			folderToSave.mkdir();
//
//			return pathToMoveErrorLog;
//		}
/*======================================== StoreEffectiveLog Methods ======================================================
 * 
 * */
		public void storeEffectiveLog(FileManager fmg,String pathFromLogs,String pathToLogs,File logFile) {
			try{
//				File logFolder=new File(pathFromLogs);
//				logFolder.mkdir();	
				
//				File logFile=this.getLog(logFolder);
				
				String today = getDay();

				String pathToMoveEfficientLog=this.generateFolder2SaveLog(AutomateImport.FOLDER_EFFICIENTLOGS,pathToLogs,today);
							
				System.out.println("MOVE TO "+pathToMoveEfficientLog);
	
				fmg.moveFile(logFile, pathToMoveEfficientLog);
				
				System.out.println("Moved: "+logFile.getName()+" to: "+pathToMoveEfficientLog);		
				
			}catch(Exception e){
				e.printStackTrace();
			}
		}
/*-----------------------------------------------------------------------------------------------------------------*/
		public String generateFolder2SaveLog(String logFolder,String pathToMoveEfficientLog,String today) throws IOException{
			pathToMoveEfficientLog=pathToMoveEfficientLog+today+"/";
			System.out.println(pathToMoveEfficientLog);
			File folderToSave=new File(pathToMoveEfficientLog);
			folderToSave.mkdir();
			
			pathToMoveEfficientLog=pathToMoveEfficientLog+logFolder+"/";
			folderToSave=new File(pathToMoveEfficientLog);
			folderToSave.mkdir();
			
			return pathToMoveEfficientLog;
		}
	/*-----------------------------------------------------------------------------------------------------------------*/

		public String getDay() {
			DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
			Calendar cal = Calendar.getInstance();
			String today=dateFormat.format(cal.getTime());
			return today;
		}
		
	/*============================================================================================================*/	

}
	
	 
//	class DBase
//	{
//	    public DBase()
//	    {
//	    }
//	 
//	    public Connection connect(String db_connect_str, 
//	  String db_userid, String db_password)
//	    {
//	        Connection conn;
//	        try 
//	        {
//	            Class.forName("com.mysql.jdbc.Driver").newInstance();
//	 
//	            conn = DriverManager.getConnection(db_connect_str, db_userid, db_password);
//	        
//	        }
//	        catch(Exception e)
//	        {
//	            e.printStackTrace();
//	            conn = null;
//	        }
//	 
//	        return conn;    
//	    }
//	    
//	    
//	    public void importData(Connection conn,String path,String tablename)
//	    {
//	        Statement stmt;
//	        String query;
//	 
//	        try
//	        {
//	            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//	            query = "LOAD DATA LOCAL INFILE '"+path+"' " +
//	            		"INTO TABLE "+tablename+";";
//	            stmt.executeUpdate(query);
//	            System.out.println(path+"-"+tablename+". Success");
//	        }
//	        catch(Exception e)
//	        {
//	            e.printStackTrace();
//	            stmt = null;
//	        }
//	    }
//	    
//	};


